package com.pay.game.central.system.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pay.game.central.system.bean.Role;
import com.pay.game.central.system.bean.User;
import com.pay.game.central.system.mapper.RoleMapper;
import com.pay.game.central.system.mapper.UserMapper;
import com.pay.game.central.utils.myIdGen.MyIDGenerator;
import com.pay.game.central.utils.myIdGen.exception.MaxIDException;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    public User getUserByNamePwd(String name, String password){
        return userMapper.getUserByNamePwd(name, password);
    }


    public User geValidateInfoById(String id){
        return userMapper.geValidateInfoById(id);
    }

    public JSONObject getUserInfo(String id){
        User user = userMapper.findUserById(id);
        List<Role> roles = roleMapper.findRoleByUserId(id);
        JSONObject object = new JSONObject();
        object.put("name",user.getName());
        object.put("username", user.getUsername());
        object.put("password", user.getPassword());
        object.put("id", user.getId());
        object.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        object.put("roles",roles.stream().map(Role::getName).collect(Collectors.toList()));
        return object;
    }

    public User getUserDetail(String id){
        return userMapper.findUserById(id);
    }

    public User findUserByUserName(String username){
        return userMapper.findUserByUserName(username);
    }

    /**
     * 模糊查询用户
     */
    public List<User> list(String username, String name,String tel, String rootId){
        return userMapper.list(username, name, tel, rootId);
    }

    /**
     * 模糊查询用户
     */
    public List<Map<String, Object>> listRoot(){
        return userMapper.listRoot();
    }

    /**
     * 用户登录状态
     */
    public void userLogin(String id){
        userMapper.setUserOnlineState(true,id);
    }

    /**
     * 用户登出状态
     */
    public void userLogout(String id){
        userMapper.setUserOnlineState(false,id);
    }

    public void updateUserInfo(User user){
        userMapper.updateUserInfo(user);
    }

    public List<Role> listRole(String userId){
        return userMapper.listRole(userId);
    }

    public void setRoles(String userId, List<Integer> roleIds){
        for (Integer roleId : roleIds) {
            userMapper.addRole(userId, roleId);
        }
    }

    public String addUser(JSONObject jsonObject){
        User user = new User();
        String pid = jsonObject.getString("pid");
        String lastId = getChildrenLastId(pid);
        if (StringUtils.isEmpty(lastId)){
            user.setId(pid + MyIDGenerator.getFirstId());
        }else {
            String startChar=lastId.substring(0,lastId.length()-4);
            String endChar = lastId.substring(lastId.length()-4);
            try {
                user.setId(startChar+MyIDGenerator.getNextId(endChar));
            } catch (MaxIDException e) {
                return "maxIdNumError";
            }
        }
        String alipay = jsonObject.getString("alipay");
        user.setAlipay(StringUtils.isEmpty(alipay) ? "" : alipay);

        String wechat = jsonObject.getString("wechat");
        user.setWechat(StringUtils.isEmpty(wechat) ? "" : wechat);

        String tel = jsonObject.getString("tel");
        user.setTel(StringUtils.isEmpty(tel) ? "" : tel);

        String paycode = jsonObject.getString("paycode");
        user.setPay_code(StringUtils.isEmpty(paycode) ? "" : paycode);

        user.setName(jsonObject.getString("name"));
        user.setUsername(jsonObject.getString("username"));
        user.setPassword(jsonObject.getString("password"));

        if (StringUtils.isEmpty(pid)){
            user.setLevel(1);
            user.setPid("");
        }else {
            user.setLevel(jsonObject.getInteger("level"));
            user.setPid(pid);
        }
        userMapper.addUser(user);

        //添加角色
        JSONArray jsonArray1 = jsonObject.getJSONArray("roles");
        if ( null != jsonArray1 && !jsonArray1.isEmpty() ){
            List<Integer> roles = jsonArray1.stream().map(obj->Integer.parseInt(obj.toString())).collect(Collectors.toList());
            setRoles(user.getId(), roles);
        }
        return "success";
    }

    public void deleteUserById(String id){
        userMapper.deleteUserById(id);
    }


    public void setScore(String id, int score){ userMapper.setScore(id, score); }

    public void updateUserPause(String id, int pause){
        userMapper.updateUserPause(id, pause);
    }

    public void removeRole(String userId, String roleId){
        userMapper.removeRole(userId, roleId);
    }

    public void removeUserAllRoles(String userId){
        userMapper.removeUserAllRoles(userId);
    }

    public void setPid(String id, String pid){
        userMapper.setPid(id,pid);
    }

    public void setInterestRate(float interestRate, String id){
        userMapper.setInterestRate(interestRate, id);
    }

    public String getChildrenLastId(String pid){
        return userMapper.getChildrenLastId(pid);
    }

    public List<Map> getManageInfo(String id) {
        return userMapper.getManageInfo(id);
    }

    public void editManageInfo(String id, int score, float interest_rate, int order_limit){
        userMapper.editManageInfo(id, score,interest_rate, order_limit);
    }
}
